//
//  LSStatusViewModel.swift
//  新浪微博---01次
//
//  Created by 李宗帅 on 16/5/7.
//  Copyright © 2016年 LS. All rights reserved.
//

import UIKit

class LSStatusViewModel: NSObject {

    //微博单条数据的viweModel
    var status :LSStatus?
    
    //返回转发数据
    var reposts_String:String?{
        
        return status?.reposts_count == 0 ? ("转发") :(dealCount(status?.reposts_count))
    }
    
    var goods_Sting:String?{
        return status?.attitudes_count == 0 ? ("点赞"):(dealCount(status?.attitudes_count))
    }
    
    
    var comments_sting:String?{
        return status?.comments_count == 0 ? ("评论"):(dealCount(status?.comments_count))
    }
    
    var levelImage: UIImage?{
        if status?.user?.mbrank >= 1 || status?.user?.mbrank > 7 {
        
            return UIImage(named: "common_icon_membership_level\(status?.user?.mbrank ?? 0)")
        }
        return nil
    }
    
    //认证
    var verifityImage:UIImage?{
        
        guard let type = status?.user?.verified_type else {
            return UIImage(named: "")
        }
        switch type {
        case -1: return nil
        case 0: return UIImage(named: "avatar_vip")
        case 1,2,3,5:return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
            
            //swfit里必须加default
        default :return UIImage(named: "")
        }
        
    }
    
    //头像加载
    var profile_url :NSURL? {
        if let url = status?.user?.profile_image_url {
            
            return NSURL(string: url)
        } else {
            return NSURL(string: "")
        }
    }
    
    //转发微博的数据
    var retweet_String :String? {
        
        return status?.retweeted_status?.text
    }
    
    //转发微博的配图
    var retweet_pic_urls:[LSPhotoViewModel]? {
        
        return status?.retweeted_status?.pic_urls
    }
    
    //来源字符串
    var source_string: String? {
        return dealSource(status?.source)
    }
    
    
    //发布时间
    var createat_string: String? {
    
        return dealCraeateTime(status?.created_at)
    }
    
    
    
    init(model: LSStatus){
        self.status = model
        super.init()
    }
    
    private func dealCount(count: Int?) ->String{
        guard let num = count else {
            return ""
        }
 
        if count < 10000 {
            return "\(num)"
        } else{
            
            let show = Float(count!) / 1000.0
            
            return String(format: "%.2f万", show)
        }
        
    }
    
    private func dealSource(source: String?) -> String {
        guard let sourceStr = source else {
            return ""
        }
        
        let subSoureArray = sourceStr.componentsSeparatedByString(">")
        
        //判断一下
        if subSoureArray.count >= 2 {
            let lastSubArray = subSoureArray[1].componentsSeparatedByString("<")
            
            if lastSubArray.count >= 1 {
                return lastSubArray[0]
            }
        }
        
        return ""
    }
    
    private func dealCraeateTime(createdate: String?) -> String {
        guard let createDate = createdate else {
            return ""
        }
        
        //1.需要把服务器给的时间,转换成一个标准四件
        let formate = NSDateFormatter()
        
        formate.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        
        formate.locale = NSLocale(localeIdentifier: "en_US")
        
        //转换成标准时间
        let date = formate.dateFromString(createDate)
        
        //显示逻辑
        //和NSCalnder进行比较
        let calnder =  NSCalendar.currentCalendar()
        
        //提供给时间比较
        //用于2个时间  需要比较哪些
        //获取枚举的单个类型
    
        //获取枚举的多个类型 用(arrayLiteral:)
        let unit = NSCalendarUnit(arrayLiteral: .Year,.Month,.Day,.Hour,.Minute)
        let cmps = calnder.components(unit, fromDate: date!, toDate: NSDate(), options: [])
        
        //发布微博的时间: 2016 - 05 - 10 03:10:30 +0000
        //系统现在时间:   2016 - 05 - 10 04:10:30 +0000
        
        if cmps.year == 0 {
            //是今年
            if cmps.month == 0 {
                //是本月
                if cmps.day == 0 {
                    //是今天
                    if cmps.hour == 0 {
                        //是本小时
                        if cmps.minute <= 0 {
                            return "刚刚"
                        } else {
                            return "\(cmps.minute)分钟之前"
                        }
                    } else {
                        //其他小时
                        return "\(cmps.hour)小时之前"
                    }
                } else if cmps.day == 1 {
                    //是昨天
                    formate.dateFormat = "HH:mm"
                    let str = formate.stringFromDate(date!)
                    return "昨天\(str)"
                } else {
                    //本月的其他天
                    return "\(cmps.day)天前"
                }
            } else {
                //不是本月
                formate.dateFormat = "MM-dd HH:mm"
                return formate.stringFromDate(date!)
            }
        } else {
            //不是今年
            formate.dateFormat = "EEE-MM-dd HH:mm"
            return formate.stringFromDate(date!)
        }
        
    }
    
    func dealAttributeString(text: String?) -> NSAttributedString?{
        
        // [馋嘴] -> 转换成一个图片
        // 获取了Emoticon实例 -> 通过HMTextAttachment.getEmoticonAttributeString 这个方法,把 图片转换成 Attribute
        guard let temp = text else {
            
            return nil
        }
        
        let tempAttribute = NSMutableAttributedString(string: temp)
        
        /*
        {
        NSAttachment = "<WeiBo.HMTextAttachment: 0x7fa3cadb1e50>";
        NSFont = "<UICTFont: 0x7fa3cc9912f0> font-family: \".SFUIText-Regular\"; font-weight: normal; font-style: normal; font-size: 16.00pt";
        }aaaaa{
        NSFont = "<UICTFont: 0x7fa3cc9912f0> font-family: \".SFUIText-Regular\"; font-weight: normal; font-style: normal; font-size: 16.00pt";
        }
        */
        
        /*
        
        . 匹配任意字符，除了换行
        
        () 锁定要查找的内容
        
        * 匹配任意长度的内容
        
        ？尽量少的匹配
        
        [] 正则的关键字
        
        */
        // 匹配正则 -- 注意 转义字符 \ (\ 也是转义字符 所以用 \\)
        let pattern = "\\[.*?\\]"
        
        // throws 这个是针对异常的操作
        /*
        try
        分三种 默认try 你可以捕获异常,或者在 catch里做一些操作
        可选  try?
        非可选 try!
        */
        
        do{
            
            // 1. 创建一个正则的查找
            let regx = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
            // 2. 去查找,返回查找结果集
            let resluts = regx.matchesInString(temp, options: [], range: NSMakeRange(0, temp.characters.count))
            
            // 3. 对结果集进行遍历,反向遍历
            var count = resluts.count
            while count > 0 {
                
                
                
                let result = resluts[--count]
                
                let emoticonStr = (temp as NSString).substringWithRange(result.range)
                
                // 目标就是在字符串里 找到 [馋嘴]
                
                // 在哪里去找 [馋嘴] -> HMEmoticon
                if let emoticon = LSEmoticonManager.searchEmoticon(emoticonStr){
                    
                    let imageAttribute =  LSTextAttachment.getEmoticonAttributeString(emoticon, fontHeigth: 16)
                    
                    // string的替换方法,没有 range
                    //                    temp.replaceRange(<#T##subRange: Range<Index>##Range<Index>#>, with: <#T##C#>)
                    
                    // 我们把 附件的东西,替换了 [馋嘴]
                    tempAttribute.replaceCharactersInRange(result.range, withAttributedString: imageAttribute)
                }
            }
            //            for i in 0..<resluts.count{
            //               //  NSTextCheckingResult 我们用到一个 range
            //
            //                let result = resluts[i]
            //
            //                print(result.range)
            //                let emoticonStr = (temp as NSString).substringWithRange(result.range)
            //
            //                // 目标就是在字符串里 找到 [馋嘴]
            //
            //                // 在哪里去找 [馋嘴] -> HMEmoticon
            //                if let emoticon = HMEmoticonManager.searchEmoticon(emoticonStr){
            //
            //                   let imageAttribute =  HMTextAttachment.getEmoticonAttributeString(emoticon, fontHeigth: 16)
            //
            //                    // string的替换方法,没有 range
            ////                    temp.replaceRange(<#T##subRange: Range<Index>##Range<Index>#>, with: <#T##C#>)
            //
            //                    // 我们把 附件的东西,替换了 [馋嘴]
            //                   tempAttribute.replaceCharactersInRange(result.range, withAttributedString: imageAttribute)
            //                    
            //                   
            //                }
            //            }
            
            
        } catch{
            print(error)
        }
        
        
        
        
        return tempAttribute
    }

}
